package m.store.service;

import com.alibaba.fastjson.JSONObject;
import m.base.model.StoreInfo;
import m.base.model.UserInfo;
import m.base.util.LevelUtil;
import m.base.util.PowerUtil;
import m.common.model.util.*;
import m.common.service.Service;
import m.store.model.RepositoryInfo;
import m.system.cache.CacheUtil;
import m.system.exception.MException;
import m.system.util.GenerateID;
import m.system.util.ObjectUtil;
import manage.model.StatusModel;
import manage.util.DictionaryUtil;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class RepositoryInfoService extends Service {
    public void verifyRepositoryNum() throws Exception {
        int repositoryNum=1;
        List<JSONObject> ls= ModelQuery.init(RepositoryInfo.class)
                .addCollectExp("num","count(#{oid})")
                .addCondition(QueryCondition.eq("store.oid", PowerUtil.getSessionStoreOid()))
                .addCondition(QueryCondition.eq("status",StatusModel.Status_Enable))
                .queryCollect(new QueryPage(0,1));
        if(!ls.isEmpty()) repositoryNum=ls.get(0).getInteger("num");
        if(repositoryNum> LevelUtil.repositoryNum()){
            throw new MException(this.getClass(),"仓库数量已超过限制（当前商户级别限制仓库数量："+LevelUtil.repositoryNum()+"）");
        }
    }
    public void addDefault(StoreInfo store, UserInfo user) throws MException {
        RepositoryInfo model=new RepositoryInfo();
        model.setOid(GenerateID.generatePrimaryKey());
        model.setDefRepository(RepositoryInfo.Yes);
        model.setStore(store);
        model.setManageUser(user);
        model.setName("默认");
        model.setSort(1);
        model.setStatus(StatusModel.Status_Enable);
        ModelUpdateUtil.insertModel(model);
    }
    /**
     * 将用户数禁用剩num个
     */
    public void limitRepositoryNum(String storeOid,int num) throws SQLException, MException {
        List<RepositoryInfo> us= ModelQueryList.getModelList(RepositoryInfo.class,new String[]{"*"},null,
            QueryCondition.and(
                QueryCondition.eq("store.oid",storeOid),
                QueryCondition.eq("status",StatusModel.Status_Enable)
            ),QueryOrder.desc("oid")
        );
        if(us.size()<=num) return;
        List<RepositoryInfo> nl=new ArrayList<>();
        for(int i=0;i<us.size()-num;i++) nl.add(us.get(i));
        nl.forEach((item)->item.setStatus(StatusModel.Status_Disabled));
        ModelUpdateUtil.updateModels(nl.toArray(new RepositoryInfo[]{}),"status");
        DictionaryUtil.clear(RepositoryInfo.class);
        CacheUtil.clear(RepositoryInfo.class);
    }
    public String save(RepositoryInfo model) throws Exception {
        if(ObjectUtil.isEmptyOid(model)) verifyRepositoryNum();
        model.setStore(PowerUtil.getSessionStore());
        ModelQueryCheck.init(model)
                .checkNotNull("name","名称不能为空")
                .checkNotNull("manageUser.oid","请选择管理用户")
                .doCheck(false,true);
        String msg;
        if(RepositoryInfo.Yes.equals(model.getDefRepository())){
            RepositoryInfo m=new RepositoryInfo();
            m.setDefRepository(RepositoryInfo.No);
            ModelUpdateUtil.update(m,new String[]{"defRepository"}, QueryCondition.eq("store.oid",model.getStore().getOid()));
        }
        if(ObjectUtil.isEmptyOid(model)){
            model.setOid(GenerateID.generatePrimaryKey());
            ModelUpdateUtil.insertModel(model);
            msg="保存成功";
        }else{
            ModelUpdateUtil.updateModel(model,"name","defRepository","sort","manageUser.oid");
            msg="修改成功";
        }
        DictionaryUtil.clear(RepositoryInfo.class);
        CacheUtil.clear(RepositoryInfo.class);
        return msg;
    }
}
